# -*- coding: utf-8 -*-
# @Time : 2021/12/27 16:31
# @FileName: fcntlock.py
# @Mail: lizhigen1996@aliyun.com

__author__ = 'Zhigen.li'

import os
from win32con import LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY
from pywintypes import OVERLAPPED
from win32file import _get_osfhandle, LockFileEx, UnlockFileEx

LOCK_EX = LOCKFILE_EXCLUSIVE_LOCK
LOCK_SH = 0  # The default value
LOCK_NB = LOCKFILE_FAIL_IMMEDIATELY
__overlapped = OVERLAPPED()

def flock(file, flags):
    hfile = _get_osfhandle(file.fileno())
    LockFileEx(hfile, flags, 0, 0xffff0000, __overlapped)

def funlock(file):
    hfile = _get_osfhandle(file.fileno())
    UnlockFileEx(hfile, 0, 0xffff0000, __overlapped)

def lock():
    lockPath = r'C:\Config\scheduler.lock'
    if not os.path.exists(r'C:\Config'):
        os.makedirs(r'C:\Config')

    if not os.path.exists(lockPath):
        with open(lockPath, 'w')as fp:
            fp.write('')

    f = open(lockPath, "wb")
    flock(f, LOCK_EX | LOCK_NB)
    return f

def unlock(fp):
    funlock(fp)
    fp.close()

